package com.lzb.browser.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ToastUtils;
import com.lzb.browser.BaseNoModelFragment;
import com.lzb.browser.Content;
import com.lzb.browser.R;
import com.lzb.browser.adapter.CollectAdapter;
import com.lzb.browser.adapter.CollectDragAdapter;
import com.lzb.browser.bean.CollectBean;
import com.lzb.browser.databinding.FragmentCollectBinding;
import com.lzb.browser.dialog.AddCollectDialog;
import com.lzb.browser.utils.AppSpUtils;
import com.lzb.browser.utils.DragCallback;
import com.lzb.browser.utils.IconDownloadTask;
import com.lzb.browser.utils.IconUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CollectFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CollectFragment extends BaseNoModelFragment<FragmentCollectBinding> implements View.OnClickListener {

    private CollectDragAdapter collectAdapter;
    private List<CollectBean> listShow = new ArrayList<>();
    private List<CollectBean> listSel = new ArrayList<>();
    private DragCallback dragCallback;
    private boolean isEdit;

    @Override
    protected int onCreate() {
        return R.layout.fragment_collect;
    }

    @Override
    protected void initView() {
        mDataBinding.tvEdit.setOnClickListener(this);
        mDataBinding.tvAllSel.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);
        mDataBinding.tvCompelete.setOnClickListener(this);

        mDataBinding.rvCollectList.setLayoutManager(new LinearLayoutManager(mContext));
        collectAdapter = new CollectDragAdapter();
        mDataBinding.rvCollectList.setAdapter(collectAdapter);

        dragCallback = new DragCallback(collectAdapter);
        // 绑定拖动功能
        ItemTouchHelper touchHelper = new ItemTouchHelper(dragCallback);
        touchHelper.attachToRecyclerView(mDataBinding.rvCollectList);

        collectAdapter.setListener(new CollectDragAdapter.Ilistener() {
            @Override
            public void clickItem(int pos, boolean isSelected) {
                if (isSelected) {
                    listSel.add(listShow.get(pos));
                } else {
                    listSel.remove(listShow.get(pos));
                }

            }

            @Override
            public void click(int pos) {
                Intent intent = new Intent();
                intent.putExtra(Content.url, listShow.get(pos).getUrl());
                getActivity().setResult(Content.SEARCH_URL_RESULT, intent);
                getActivity().finish();
            }

            @Override
            public void clickEdit(int pos) {
                showEditDialog(pos);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvEdit) {//编辑
            if (listShow.size() == 0) return;
            isEdit = true;
            collectAdapter.setEdit(isEdit);
            dragCallback.setEdit(isEdit);
            mDataBinding.tvEdit.setVisibility(View.GONE);
            mDataBinding.llEdit.setVisibility(View.VISIBLE);
        } else if (id == R.id.tvAllSel) {//全选
            if (listShow.size() == 0) return;
            listSel.clear();
            for (CollectBean collectBean : listShow) {
                collectBean.setSelected(true);
                listSel.add(collectBean);
            }
            collectAdapter.notifyDataSetChanged();
        } else if (id == R.id.tvDelete) {//删除
            if (listSel.size() == 0) return;
            listShow.removeAll(listSel);
            AppSpUtils.saveCollectList(listShow);
            listSel.clear();
            getData();
            ToastUtils.showShort(getString(R.string.delete_suc));
        } else if (id == R.id.tvCompelete) {//完成
            isEdit = false;
            collectAdapter.setEdit(isEdit);
            dragCallback.setEdit(isEdit);
            mDataBinding.tvEdit.setVisibility(View.VISIBLE);
            mDataBinding.llEdit.setVisibility(View.GONE);
            listSel.clear();
            getData();
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        listShow.clear();
        List<CollectBean> listSp = AppSpUtils.getCollectList();
        if (listSp != null && !listSp.isEmpty()) {
            listShow.addAll(listSp);
            collectAdapter.setList(listSp);
            mDataBinding.rvCollectList.setVisibility(View.VISIBLE);
            mDataBinding.tvCollectNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvCollectList.setVisibility(View.GONE);
            mDataBinding.tvCollectNoData.setVisibility(View.VISIBLE);
        }
    }

    private void showEditDialog(int position) {
        AddCollectDialog dialog = new AddCollectDialog(mContext);
        dialog.setSaveTitle(listShow.get(position).getTitle());
        dialog.setSaveUrl(listShow.get(position).getUrl());
        dialog.setListener(new AddCollectDialog.Ilistener() {
            @Override
            public void clickConfirm(String title, String url) {
                if (title != null && url != null) {
                    // 获取网站图标URL
                    String iconUrl = IconUtils.getDefaultFaviconUrl(url);

                    // 创建收藏对象
                    CollectBean collectBean = new CollectBean(title, url, iconUrl);

                    // 获取现有的收藏列表
                    List<CollectBean> collectList = AppSpUtils.getCollectList();
                    if (collectList == null) {
                        collectList = new ArrayList<>();
                    }

                    // 检查是否已经存在相同的URL
                    boolean exists = false;
                    for (CollectBean item : collectList) {
                        if (item.getUrl().equals(url) && !item.getUrl().equals(listShow.get(position).getUrl())) {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists) {
                        collectList.get(position).setTitle(title);
                        collectList.get(position).setUrl(url);
                        collectList.get(position).setIconUrl(iconUrl);
                        // 保存到SharedPreferences
                        AppSpUtils.saveCollectList(collectList);

                        // 下载图标
                        downloadIconForCollect(collectBean);

                        listShow.get(position).setTitle(title);
                        listShow.get(position).setUrl(url);
                        listShow.get(position).setIconUrl(iconUrl);

                        collectAdapter.notifyItemChanged(position);

                        ToastUtils.showShort(getString(R.string.save_suc));
                    } else {
                        ToastUtils.showShort("该网址已在收藏中");
                    }
                } else {
                    ToastUtils.showShort("无法获取页面信息");
                }
            }
        });
        dialog.show();
    }

    /**
     * 下载收藏项的图标
     */
    private void downloadIconForCollect(CollectBean collectBean) {
        if (collectBean.getIconUrl() != null && !collectBean.getIconUrl().isEmpty()) {
            new IconDownloadTask(getActivity(), new IconDownloadTask.OnIconDownloadListener() {
                @Override
                public void onIconDownloaded(Bitmap bitmap, String iconUrl) {
                    // 将图标转换为Base64
                    String iconData = IconUtils.bitmapToBase64(bitmap);
                    if (iconData != null) {
                        collectBean.setIconData(iconData);

                        // 更新收藏列表
                        List<CollectBean> collectList = AppSpUtils.getCollectList();
                        if (collectList != null) {
                            for (int i = 0; i < collectList.size(); i++) {
                                if (collectList.get(i).getUrl().equals(collectBean.getUrl())) {
                                    collectList.set(i, collectBean);
                                    break;
                                }
                            }
                            AppSpUtils.saveCollectList(collectList);
                        }
                    }
                }

                @Override
                public void onIconDownloadFailed(String iconUrl) {
                    // 图标下载失败，使用默认图标
                    // 这里可以记录日志或显示默认图标
                    Log.e("TAG", "onIconDownloadFailed: " + iconUrl);
                }
            }).execute(collectBean.getIconUrl());
        }
    }

}